﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Configuration;
using LevenBlog.Core.Configuretion.Route;

namespace LevenBlog.Core.Install {
    public static class InstallExtensions {
        //private static readonly string _name = "levenblog_setup";
        private static readonly string _step = "levenblog_steup_step";
        private static InstallOperationCollection _operations = new InstallOperationCollection();

        public static void SetSetup(this HttpResponse response, int num) {
            //HttpCookie cookie = new HttpCookie(_name, num.ToString());
            //if (response.Cookies.AllKeys.Contains(_name))
            //    response.Cookies.Remove(_name);
            //response.Cookies.Add(cookie);
            Object obj = Cache.ObjectCache.Get(_step);
            if (obj == null) {
                obj = num;
                Cache.ObjectCache.Insert(_step, obj);
            } else {
                obj = num;
                Cache.ObjectCache.Remove(_step);
                Cache.ObjectCache.Insert(_step, obj);
            }
        }

        public static int GetSetup(this HttpRequest request) {
            //HttpCookie cookie = request.Cookies.Get(_name);
            //int step;
            //if (cookie == null)
            //    step = 0;
            //else {
            //    if (!Int32.TryParse(cookie.Value, out step)) {
            //        step = 0;
            //    }
            //}
            //return step;
            object obj = Cache.ObjectCache.Get(_step);
            int result;
            if (obj == null) {
                result = 0;
            } else if (!Int32.TryParse(obj.ToString(), out result)) {
                result = 0;
            }
            return result;
        }

        public static InstallOperationCollection GetOperations(this HttpServerUtility server) {
            return _operations;
        }

        public static void RemoveOperations(this HttpServerUtility server) {
            _operations = new InstallOperationCollection();
        }

        public static void SaveRoute(InstallConfig config) {
            Configuration webConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(
                    System.Web.HttpContext.Current.Request.ApplicationPath);
            RouteConfigurationSection section = webConfig.Sections["routeConfiguration"] as RouteConfigurationSection;
            section.Extend = config.ExtendName;
            section.Short.Enable = config.EnableShortRouting;
            webConfig.Save();
        }
    }
}
